import json
import requests

from sdk.sign import get_signature


class CTClientBuilder:
    def __init__(self):
        self._ak = None
        self._sk = None
        self._ai_app_key = None

    def with_ak(self, ak):
        self._ak = ak
        return self

    def with_sk(self, sk):
        self._sk = sk
        return self

    def with_ai_app_key(self, ai_app_key):
        self._ai_app_key = ai_app_key
        return self

    def build(self):
        return CTClient(self._ak, self._sk, self._ai_app_key)


class CTClient:
    def __init__(self, ak, sk, ai_app_key):
        self._ak = ak
        self._sk = sk
        self._ai_app_key = ai_app_key

    def request(self, method, url, headers=None, body=None):
        if headers is None:
            headers = {}
        # 调用get_signature方法获取签名
        request_id, eop_date, sign_header = get_signature(url, self._ak, self._sk, self._ai_app_key, body)
        # 生成请求header
        headers["appkey"] = self._ai_app_key
        headers["Content-Type"] = "application/json;charset=UTF-8"
        headers["ctyun-eop-request-id"] = request_id
        headers["Eop-Authorization"] = sign_header
        headers["Eop-date"] = eop_date
        headers["Host"] = "ai-global.ctapi.ctyun.cn"
        return requests.request(method, url, data=json.dumps(body), headers=headers)

